<?php

namespace System\Core;

use Smarty;

class View
{
    private static $smarty;

    public static function init()
    {
        if (!self::$smarty) {
            self::$smarty = new Smarty();

            // 配置Smarty
            self::$smarty->setTemplateDir(APP_PATH . '/views');
            self::$smarty->setCompileDir(BASE_PATH . '/templates_c');
            self::$smarty->setCacheDir(BASE_PATH . '/storage/cache');
            self::$smarty->setConfigDir(BASE_PATH . '/config/smarty');
            self::$smarty->setLeftDelimiter('{{');
            self::$smarty->setRightDelimiter('}}');

            // 开发模式配置
            if (Config::get('APP_DEBUG', false)) {
                self::$smarty->debugging = true;
                self::$smarty->caching = false;
                self::$smarty->cache_lifetime = 0;
            } else {
                self::$smarty->debugging = false;
                self::$smarty->caching = true;
                self::$smarty->cache_lifetime = 3600; // 1小时
            }

            // 添加自定义函数/过滤器
            self::addCustomFunctions();
        }
        return self::$smarty;
    }

    public static function render($template, $data = [])
    {
        $smarty = self::init();

        // 分配数据
        foreach ($data as $key => $value) {
            $smarty->assign($key, $value);
        }

        // 添加全局变量
        $smarty->assign('base_url', Config::get('APP_URL', ''));
        $smarty->assign('current_url', $_SERVER['REQUEST_URI']);

        // 渲染模板
        $content = $smarty->fetch($template . '.tpl');

        return new Response($content);
    }

    private static function addCustomFunctions()
    {
        // 示例：添加自定义修饰器
        self::$smarty->registerPlugin('modifier', 'truncate', function ($string, $length = 80) {
            if (mb_strlen($string) > $length) {
                return mb_substr($string, 0, $length) . '...';
            }
            return $string;
        });

        // 日期格式化函数
        self::$smarty->registerPlugin('modifier', 'format_date', function ($date, $format = 'Y-m-d') {
            if (!$date) return '';
            if (is_numeric($date)) {
                return date($format, $date);
            }
            return date($format, strtotime($date));
        });

        // 检查用户是否登录
        self::$smarty->registerPlugin('function', 'is_logged_in', function () {
            return !empty($_SESSION['user_id']);
        });

        // 生成CSRF令牌
        self::$smarty->registerPlugin('function', 'csrf_token', function () {
            $token = bin2hex(random_bytes(32));
            $_SESSION['csrf_token'] = $token;
            return '<input type="hidden" name="csrf_token" value="' . $token . '">';
        });
    }
}
